//
//  TransferGoodsDetailTalbeViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/7/15.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit
import ActionSheetPicker_3_0
import SVProgressHUD
class TransferGoodsDetailTalbeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, TransferGoodsHeaderCellDelegate {
   
    @IBOutlet weak var tableView: UITableView!
    
    var model: TransferDetailModel? {
        didSet {
           self.tableView.reloadData()
        }
    }
    var id: Int!
    var type: String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "转让详情"
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        let cellNib = UINib(nibName: "TransferGoodsHeaderCell", bundle: nil)
        self.tableView.registerNib(cellNib, forCellReuseIdentifier: "TransferGoodsHeaderCell")
        
        let cellNib1 = UINib(nibName: "TransferFooterCell", bundle: nil)
        self.tableView.registerNib(cellNib1, forCellReuseIdentifier: "TransferFooterCell")
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TransferGoodsDetailTalbeViewController.tableViewReload(_:)), name:transGoods_noti, object: nil)
        
        self.getGoodsInfo()
        
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
    }
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //MARK:tableViewDataSource
   
    func initRightItem(){
        
        //转发
        let ForwardBtn = UIButton(frame: CGRectMake(0, 0, 20, 20))
        ForwardBtn.setBackgroundImage(UIImage(named: "share-1-white"), forState: UIControlState.Normal)
        ForwardBtn.addTarget(self, action: #selector(self.ForwardAction), forControlEvents:  UIControlEvents.TouchUpInside)
        let Forward = UIBarButtonItem(customView: ForwardBtn)
        
        
        self.navigationItem.rightBarButtonItem = Forward
        
    }
    
    func ForwardAction(sender: UIButton){
        self.shareAction(sender)
        
    }
    
    //MARK:MobShare
    func shareAction(sender: UIButton){

        let shareParames = NSMutableDictionary()
        let url = String(format: "%@transfer/wupin/fenxiang/\(self.model!.id)",BaseUrl)
        shareParames.SSDKSetupShareParamsByText("",
                                                images : UIImage(named: "ShareImg.png"),
                                                url : NSURL(string:url),
                                                title : self.model?.name,
                                                type : SSDKContentType.Auto)
        
        
        //2.进行分享
        SSUIShareActionSheetStyle.setShareActionSheetStyle(ShareActionSheetStyle.Simple)
        
        ShareSDK.showShareActionSheet(sender, items: nil  , shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, end) -> Void in
            
            switch state{
                
            case SSDKResponseState.Success: print("分享成功")
            case SSDKResponseState.Fail:    print("分享失败,错误描述:\(error)")
            case SSDKResponseState.Cancel:  print("分享取消")
                
            default:
                break
            }
        }
        
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.model == nil{
            return 0
        }else{
            if self.model?.rmlist.count == 0{
                return 1
            }else{
                return 2
            }

        }
        
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row == 0{
            if self.model == nil{
                return 0
            }else{
                let font = UIFont(name: "Helvetica", size: 16)
                let height = publicMethod.getLabHeigh((self.model?.body)!, font: font!, width: SCREEN_WIDTH - 16) + 29 + 15
                
                return 520 + height
            }
            
        }else{
            if self.model?.rmlist.count == 0 || self.model?.rmlist.count == nil{
                return 0
            }else{
                return CGFloat((self.model?.rmlist.count)! * 100 + 31)
            }
            
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCellWithIdentifier("TransferGoodsHeaderCell", forIndexPath: indexPath) as! TransferGoodsHeaderCell
            cell.delegate = self
            cell.model = self.model
            cell.selectionStyle = UITableViewCellSelectionStyle.None
            return cell
        }else{
            let cell = tableView.dequeueReusableCellWithIdentifier("TransferFooterCell", forIndexPath: indexPath) as! TransferFooterCell
            cell.modelList = (self.model?.rmlist)!
            return cell
        }
        
    }
    
    
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    //MARK:networking
    func getGoodsInfo(){
        DataTool.loadTransferDetailData(id, type: type, completionHandler: { (newModel) in
            guard let newDataes = newModel else {
                return
            }
            self.initRightItem()
            self.model = newDataes
            self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0,inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
        })
    }
        
    //MARK:TransferGoodsHeaderCellDelegate
    func callAction(text: String){
        publicMethod.callPhone(text, withSuperView: self.view)
        
    }
    func reportAction(text: String){
        ActionSheetMultipleStringPicker.showPickerWithTitle("举报", rows:[["电话虚假(如空号、无人接听)", "诈骗(个人虚假信息)", "虚假(如产品、价格等虚假)","涉黄违法","其他"]],initialSelection: [1,1], doneBlock: {
            picker, values, indexes in
            let obj = (indexes as! NSArray)[0] as! String
            let url = String(format: "%@hzpreport/dosave",BaseUrl)
            let paramDic = ["msg": obj, "reportid": String(self.model!.id), "type": "业内转让"]
            DataTool.reportDetail(url, param: paramDic, completionHandler: ({(newModel) in
                guard newModel != nil else {
                    return
                }
                SVProgressHUD.showSuccessWithStatus(newModel?.msg)
                
            }))
            
            return
            }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
        

    }
    func ivSelected() {
        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeTableViewController") as! UserHomeTableViewController
        
        vc.userId = Int((model?.userid)!)
        self.navigationController?.pushViewController(vc, animated: true)
    }

    //MARK:noti
    func tableViewReload(notification:NSNotification){
        
        let id = notification.object?.valueForKey("id") as? Int
        let type = notification.object?.valueForKey("type") as? String
        
        self.id = id
        self.type = type
        self.getGoodsInfo()
        
    }

}
